package com.smit.update.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.smit.bean.UpdatePackageBean;
import com.smit.common.UpdateManager;
import com.smit.update.activity.UpdateActivity;
import com.smit.utils.NetUtil;

import java.io.File;
import java.util.Locale;

public class UpdateService extends Service {
    final String TAG = "UpdateService";
    Handler handler;
    long TIME_FOR_CHECK = 48 * 3600 * 1000L;
    Thread checkThread;
    UpdateManager updateManager;

    public UpdateService() {

    }

    @Override
    public void onCreate() {
        updateManager = UpdateManager.getInstance(this.getApplicationContext());
        handler = new Handler();
        startCheckThread();
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    private void startCheckThread() {
        //启动后台，自动检测升级
        if (checkThread == null) {
            checkThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            if (!updateManager.getHasDownloaded() && !updateManager.getIsDownloading()) {
                                //这里检查是否下载完成，前台是否在下载，如果没有就要启动下载，
                                if (NetUtil.isNetworkOk(UpdateService.this)
                                        && (NetUtil.isEthernetOn(UpdateService.this) || NetUtil.isWifiConnected(UpdateService.this))) {
                                    if(updateCheck()){
                                        downloadFile();
                                    }
                                } else {
                                    Log.d(TAG, "network not ok for update check, retry in 10 sec");
                                    Thread.sleep(10000);
                                }
                            } else {
                                Log.d(TAG, "check update in 48 hours");
                                Thread.sleep(TIME_FOR_CHECK);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
            checkThread.setName("smit_osupdate");
            checkThread.start();
        }
    }

    private boolean updateCheck() {
        UpdatePackageBean updatePackageBean = updateManager.getUpdatePackageBean();
        if (updatePackageBean != null && updatePackageBean.getSize() > 0) {
            return true;
        }
        RequestCallBack<String> requestCallBack = new RequestCallBack<String>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                UpdatePackageBean updatePackageBean = updateManager.getUpdatePackageBean();
                if (updatePackageBean != null && updatePackageBean.getSize() > 0) {
                    int networkType = NetUtil.getNetworkClass(UpdateService.this);
                    if (networkType == NetUtil.NETWORK_TYPE_ETHERNET
                            || networkType == NetUtil.NETWORK_TYPE_WIFI) {
                        downloadFile();
                    } else if (networkType == NetUtil.NETWORK_CLASS_4_G) {
                        startUpdateInfoActivity();
                    }
                } else {
                    Log.d(TAG, "update check success and no packages");
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.d(TAG, "update check fail with error : " + msg);
            }
        };
        updateManager.checkUpdate(requestCallBack);
        return false;
    }


    private void downloadFile() {
        RequestCallBack<File> requestCallBack = new RequestCallBack<File>() {
            @Override
            public void onStart() {
            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                String percentStr = String.format(Locale.getDefault(), "%d%%", current * 100 / total);
                Log.d(TAG, "update file downloaded " + percentStr);
            }

            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
                startUpdateInfoActivity();
            }

            @Override
            public void onFailure(HttpException e, String s) {
            }
        };
        updateManager.downloadFile(requestCallBack);
    }

    private void startUpdateInfoActivity() {
        Intent intent = new Intent(this, UpdateActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }
}
